<template>
    <div class="h-full p-6 rounded-lg bg-body" @click.stop="powerState.visible = false">
        <h2 class="text-2xl mb-4">团队管理</h2>

        <div class="my-2">
            <el-button
                type="primary"
                plain
                :disabled="pager.loading || (know.power < permissionEnum.ADMIN)"
                @click="memberPopup = true"
            >+ 添加成员</el-button>
        </div>

        <el-table v-loading="pager.loading" :data="pager.lists" size="large">
            <el-table-column label="成员信息" prop="user" min-width="160">
                <template #default="scope: { row: TeamedMemberResponse }">
                    <div class="flex items-center">
                        <el-avatar :src="scope.row.user_avatar" style="flex-shrink: 0;" />
                        <div class="ml-2">
                            <div>
                                <span>{{ scope.row.user_nickname }}</span>
                                <el-tag
                                    v-if="scope.row.user_sn === currUserSn"
                                    type="primary"
                                    size="small"
                                    class="ml-2"
                                >
                                    我
                                </el-tag>
                            </div>
                            <p class="text-xs text-tx-placeholder">{{ scope.row.user_sn }}</p>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="身份角色" prop="identity" min-width="100">
                <template #default="scope: { row: TeamedMemberResponse }">
                    <span>{{ scope.row.power === 4 ? '拥有者' : '成员' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="所属权限" prop="power" min-width="100">
                <template #default="scope: { row: TeamedMemberResponse }">
                    <el-popover
                        :width="380"
                        :show-arrow="false"
                        :visible="checkPermissionPopover(scope.row)"
                        trigger="click"
                        placement="bottom-end"
                        transition="custom-popover"
                    >
                        <div
                            v-for="(item, index) in permissionList"
                            :key="index"
                            class="flex items-center cursor-pointer p-4 hover:bg-page rounded-xl"
                            @click.stop="handleUpdate(scope.row.id, item.power)"
                        >
                            <div style="width: 320px">
                                <div class="text-base text-tx-primary">{{ item.title }}</div>
                                <div class="text-xs text-tx-placeholder mt-2">
                                    {{ item.tips }}
                                </div>
                            </div>
                            <el-radio
                                v-model="scope.row.power"
                                :value="item.power"
                                size="large"
                            />
                        </div>
                        <template #reference>
                            <div class="flex items-center">
                                <span v-if="scope.row.power === permissionEnum.VIEW">可查看</span>
                                <span v-if="scope.row.power === permissionEnum.EDIT">可编辑</span>
                                <span v-if="scope.row.power === permissionEnum.ADMIN">可管理</span>
                                <span v-if="scope.row.power === permissionEnum.OWNED">所有权</span>
                                <icon
                                    v-if="checkPermissionPopover(scope.row, 'button')"
                                    name="el-icon-Edit"
                                    class="ml-1 cursor-pointer"
                                    @click.stop="showPermissionPopover(scope.row)"
                                />
                            </div>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="加入时间" prop="create_time" min-width="175" />
            <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope: { row: TeamedMemberResponse }">
                    <el-button
                        v-if="know.power >= permissionEnum.ADMIN && scope.row.user_sn !== currUserSn"
                        :disabled="scope.row.power >= permissionEnum.ADMIN && know.power !== permissionEnum.OWNED"
                        type="primary"
                        link
                        @click="handleDelete(scope.row.id, scope.row.user_nickname)"
                    >移出团队</el-button>
                    <el-button
                        v-else-if="scope.row.user_sn === currUserSn && scope.row.id > 0"
                        type="primary"
                        link
                        @click="handleExits()"
                    >退出团队</el-button>
                </template>
            </el-table-column>
        </el-table>

        <popup-team-add
            type="know"
            :code="know.code"
            :show="memberPopup"
            @close="memberPopup = false"
            @confirm="handleCreate"
        />
    </div>
</template>

<script setup lang="ts">
import { permissionEnum } from '~/enums/app'
import useUserStore from '~/stores/user'
import knowTeamedApi from '~/api/agent/know/teamed'
import PopupTeamAdd from '../../_components/popup-team-add.vue'

const props = withDefaults(
    defineProps<{
        know: KnowManageDetailResponse
    }>(),
    {}
)

const router = useRouter()

// 权限列表
const permissionList = [
    {power: permissionEnum.VIEW, title: '查看权', tips: '仅允许查看知识库数据'},
    {power: permissionEnum.EDIT, title: '编辑权', tips: '添加和修改知识库数据'},
    {power: permissionEnum.ADMIN, title: '管理权', tips: '管理知识库|数据|资料|团队'}
]

// 基础信息
const memberPopup = ref<boolean>(false)
const powerState = reactive({ visible: false, memberId: 0 })
const currUserSn = computed(() => useUserStore().users.sn)

// 搜索条件
const queryParams = reactive({
    ap_code: props.know.code
})

// 分页查询
const { pager, queryLists } = usePaging({
    fetchFun: knowTeamedApi.lists,
    params: queryParams
})

/**
 * 添加团队成员
 *
 * @param data
 * @author zero
 */
const handleCreate = async (data: any) => {
    if (data.length > 0) {
        for (const item of data) {
            await knowTeamedApi.add({
                ap_code: props.know.code,
                user_sn: item.sn,
                power: item.power
            })
        }

        memberPopup.value = false
        feedback.msgSuccess('添加成功')
        await nextTick()
        await queryLists()
    }
}

/**
 * 更新成员权限
 *
 * @param id
 * @param power
 * @author zero
 */
const handleUpdate = async (id: number, power: number) => {
    await knowTeamedApi.edit({id, power})
    await queryLists()
    resetPermissionPopover()
    feedback.msgSuccess('修改成功')
}

/**
 * 移除团队成员
 *
 * @param {number} id
 * @param {string} nickname
 * @author zero
 */
const handleDelete = async (id: number, nickname: string) => {
    feedback.confirm('确定要把《' + nickname + '》移出团队吗?')
        .then(async () => {
            await knowTeamedApi.delete(id)
            await queryLists()
            feedback.msgSuccess('移出成功')
        }).catch(() => {})
}

/**
 * 退出当前团队
 *
 * @author zero
 */
const handleExits = async () => {
    feedback.confirm('确定要退出团队吗?')
        .then(async () => {
            await knowTeamedApi.exits(props.know.code)
            feedback.msgSuccess('退出成功')
            await router.push({ path: '/agent/know' })
        }).catch(() => {})
}

/**
 * 权限弹窗验证
 */
const checkPermissionPopover = (row: any, type: string = 'popover') => {
    if (type === 'popover') {
        return powerState.visible && powerState.memberId === row.id
    }

    if (
        props.know.power === permissionEnum.OWNED
        && row.power !== permissionEnum.OWNED
    ) {
        return true
    }

    return props.know.power >= permissionEnum.ADMIN
        && row.user_sn !== currUserSn.value
        && row.power < permissionEnum.ADMIN
}

/**
 * 权限弹窗显示
 */
const showPermissionPopover = (row: any) => {
    powerState.visible = true
    powerState.memberId = row.id
}

/**
 * 权限弹窗重置
 */
const resetPermissionPopover = () => {
    powerState.visible = false
    powerState.memberId = 0
}

onMounted(async () => {
    await queryLists()
})
</script>
